package com.cloud.bc.controller.ajax;

import com.cloud.bc.model.domain.UserInfo;
import com.cloud.bc.model.entity.BcSingleLocations;
import com.cloud.bc.model.enums.CookieConst;
import com.cloud.bc.model.request.SetLocationRequest;
import com.cloud.bc.model.response.AjaxResp;
import com.cloud.bc.service.BcSingleLocationsService;
import com.cloud.bc.service.BcUsersService;
import com.cloud.common.util.CookieUtils;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 定位
 */
@AllArgsConstructor
@RestController
@RequestMapping("ajax/position")
public class Ajax_PositionController {

    private final BcUsersService bcUsersService;
    private final BcSingleLocationsService bcSingleLocationsService;

    @PostMapping("updateLocation")
    public AjaxResp updateLocation(SetLocationRequest req, HttpServletRequest request, HttpServletResponse response) {
        AjaxResp ajaxResp = new AjaxResp();

        UserInfo userInfo = bcUsersService.getUserInfo(request);
        if (null != userInfo && null !=userInfo.getId() && userInfo.getId().intValue()>0) {
            BcSingleLocations bcSingleLocations = new BcSingleLocations();
            bcSingleLocations.setUserId(userInfo.getId());
            bcSingleLocations.setDistrictCn(req.getCity());
            bcSingleLocations.setLatitude(req.getLat());
            bcSingleLocations.setLongitude(req.getLng());
            boolean result = bcSingleLocationsService.upsert(bcSingleLocations);
            if(!result){
                ajaxResp.setMsg("更新坐标失败");
                ajaxResp.setSuccess(false);
                return ajaxResp;
            }
        }
        return ajaxResp;
    }

    @PostMapping("setLocationCookie")
    public AjaxResp setLocationCookie(String value,HttpServletRequest request, HttpServletResponse response){
        CookieUtils.setCookie(request,response, CookieConst.location,value);
        return  new AjaxResp();
    }

}
